package logic

import (
	"context"
	"king/model/mysql"

	"king/kingrpc/internal/svc"
	"king/kingrpc/kingrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductListLogic) ProductList(in *kingrpc.ProductListRequest) (*kingrpc.ProductListResponse, error) {
	// todo: add your logic here and delete this line
	offset := (in.Page - 1) * in.Size
	var products []mysql.Product
	sk := mysql.DB.Debug().Model(mysql.Product{}).Offset(int(offset)).Limit(int(in.Size))
	if in.PriceOrder == 1 {
		sk = sk.Order("price desc")
	}

	if in.PriceOrder == 2 {
		sk = sk.Order("price asc")
	}

	if in.Start > 0 {
		sk = sk.Where("stock>=?", in.Start)
	}

	if in.End > 0 {
		sk = sk.Where("stock<=?", in.End)
	}
	sk.Find(&products)

	var productList []*kingrpc.ProductList

	for _, product := range products {
		list := kingrpc.ProductList{
			Title:     product.Title,
			Price:     float32(product.Price),
			Stock:     product.Stock,
			Sales:     product.Sales,
			Image:     product.Image,
			ProductId: int64(product.ID),
		}
		productList = append(productList, &list)
	}
	return &kingrpc.ProductListResponse{
		List: productList,
	}, nil
}
